// 对话管理服务
import axios from 'axios';

// API日志工具导入
import apiLogger from '@utils/apiLogger';

// 创建axios实例并集成日志
const api = axios.create({
  baseURL: process.env.REACT_APP_API_URL || 'http://localhost:6001',
  headers: {
    'Content-Type': 'application/json',
  },
});

// 集成API日志记录
apiLogger.createAxiosInterceptors(api);

// 对话状态枚举
export enum ConversationStatus {
  Active = 'active',
  Closed = 'closed',
  Archived = 'archived',
  Deleted = 'deleted'
}

// 消息角色枚举
export enum ConversationMessageRole {
  User = 'user',
  Assistant = 'assistant',
  System = 'system'
}

// 对话DTO接口
export interface ConversationDto {
  id: string;
  agentId: string;
  agentName: string;
  title: string;
  description: string;
  status: ConversationStatus;
  isActive: boolean;
  messageCount: number;
  createdAt: string;
  lastMessageAt?: string;
  tags: string[];
  createdBy: string;
}

// 对话详情DTO接口
export interface ConversationDetailDto extends ConversationDto {
  messages: ConversationMessageDto[];
}

// 消息DTO接口
export interface ConversationMessageDto {
  id: string;
  conversationId: string;
  content: string;
  role: ConversationMessageRole;
  createdAt: string;
  createdBy: string;
  metadata?: Record<string, any>;
}

// 创建对话输入接口
export interface CreateConversationInput {
  agentId: string;
  title: string;
  description: string;
  initialMessage: string;
}

// 更新对话输入接口
export interface UpdateConversationInput {
  title: string;
  description: string;
  tags: string[];
  isActive?: boolean;
}

// 添加消息输入接口
export interface AddMessageInput {
  content: string;
  role: ConversationMessageRole;
  metadata?: Record<string, any>;
}

// 更新消息输入接口
export interface UpdateMessageInput {
  content: string;
  metadata?: Record<string, any>;
}

// 对话统计DTO接口
export interface ConversationStatisticsDto {
  totalConversations: number;
  activeConversations: number;
  totalMessages: number;
  statusStatistics: Record<ConversationStatus, number>;
  timestamp: string;
}

// 查询参数接口
export interface GetConversationListInput {
  filter?: string;
  agentId?: string;
  status?: ConversationStatus;
  isActive?: boolean;
  skipCount: number;
  maxResultCount: number;
  sorting?: string;
}

// 获取对话列表
export async function getConversationList(params: GetConversationListInput): Promise<{
  items: ConversationDto[];
  totalCount: number;
}> {
  const response = await axios.get('/api/app/conversation', {
    params
  });
  return {
    items: response.data.items || [],
    totalCount: response.data.totalCount || 0
  };
}

// 获取对话详情
export async function getConversationDetail(id: string): Promise<ConversationDetailDto> {
  const response = await axios.get(`/api/app/conversation/${id}`);
  return response.data;
}

// 创建对话
export async function createConversation(input: CreateConversationInput): Promise<ConversationDto> {
  const response = await axios.post('/api/app/conversation', input);
  return response.data;
}

// 更新对话
export async function updateConversation(id: string, input: UpdateConversationInput): Promise<ConversationDto> {
  const response = await axios.put(`/api/app/conversation/${id}`, input);
  return response.data;
}

// 删除对话
export async function deleteConversation(id: string): Promise<void> {
  await axios.delete(`/api/app/conversation/${id}`);
}

// 添加消息
export async function addMessage(conversationId: string, input: AddMessageInput): Promise<ConversationMessageDto> {
  const response = await axios.post(`/api/app/conversation/${conversationId}/messages`, input);
  return response.data;
}

// 获取对话消息列表
export async function getConversationMessages(conversationId: string): Promise<ConversationMessageDto[]> {
  const response = await axios.get(`/api/app/conversation/${conversationId}/messages`);
  return response.data || [];
}

// 更新消息
export async function updateMessage(messageId: string, input: UpdateMessageInput): Promise<ConversationMessageDto> {
  const response = await axios.put(`/api/app/conversation/messages/${messageId}`, input);
  return response.data;
}

// 删除消息
export async function deleteMessage(messageId: string): Promise<void> {
  await axios.delete(`/api/app/conversation/messages/${messageId}`);
}

// 获取对话统计
export async function getConversationStatistics(agentId?: string): Promise<ConversationStatisticsDto> {
  const response = await axios.get('/api/app/conversation/statistics', {
    params: { agentId }
  });
  return response.data;
}

// 关闭对话
export async function closeConversation(id: string): Promise<void> {
  await axios.post(`/api/app/conversation/${id}/close`);
}

// 重新打开对话
export async function reopenConversation(id: string): Promise<void> {
  await axios.post(`/api/app/conversation/${id}/reopen`);
}

// 对话状态显示映射
export const conversationStatusMap = {
  [ConversationStatus.Active]: { text: '进行中', color: 'success' },
  [ConversationStatus.Closed]: { text: '已关闭', color: 'default' },
  [ConversationStatus.Archived]: { text: '已归档', color: 'warning' },
  [ConversationStatus.Deleted]: { text: '已删除', color: 'error' }
};

// 消息角色显示映射
export const messageRoleMap = {
  [ConversationMessageRole.User]: { text: '用户', color: 'blue' },
  [ConversationMessageRole.Assistant]: { text: '助手', color: 'green' },
  [ConversationMessageRole.System]: { text: '系统', color: 'gray' }
};

// 导出服务对象
const conversationService = {
  ConversationStatus,
  ConversationMessageRole,
  conversationStatusMap,
  messageRoleMap,
  getConversationList,
  getConversationDetail,
  createConversation,
  updateConversation,
  deleteConversation,
  addMessage,
  getConversationMessages,
  updateMessage,
  deleteMessage,
  getConversationStatistics,
  closeConversation,
  reopenConversation,
  // 别名方法
  getConversation: getConversationDetail,
  sendMessage: addMessage,
  getConversationStats: getConversationStatistics
};

export default conversationService;